import { BackupManager } from './backup.js';
import { CloudBackupManager } from './cloudBackup.js';

class BackupScheduler {
  constructor() {
    this.tasks = new Map();
    this.backupManager = new BackupManager();
    this.timers = new Map();
  }

  // 解析简单的cron表达式（仅支持基本格式）
  parseSimpleCron(cronExpression) {
    // 简化版本，只支持 "分 时 日 月 周" 格式中的基本设置
    const parts = cronExpression.split(' ');
    if (parts.length !== 5) {
      throw new Error('Invalid cron expression format');
    }
    
    return {
      minute: parts[0],
      hour: parts[1],
      day: parts[2],
      month: parts[3],
      dayOfWeek: parts[4]
    };
  }

  // 计算下次执行时间
  getNextExecutionTime(cronExpression) {
    try {
      const cron = this.parseSimpleCron(cronExpression);
      const now = new Date();
      const next = new Date(now);
      
      // 设置分钟
      if (cron.minute !== '*') {
        next.setMinutes(parseInt(cron.minute));
      }
      
      // 设置小时
      if (cron.hour !== '*') {
        next.setHours(parseInt(cron.hour));
      }
      
      // 如果时间已过，则设置为明天
      if (next <= now) {
        next.setDate(next.getDate() + 1);
      }
      
      return next;
    } catch (error) {
      console.error('解析cron表达式失败:', error);
      // 默认1小时后执行
      return new Date(Date.now() + 60 * 60 * 1000);
    }
  }

  // 启动定时备份任务
  startScheduledBackup(cronExpression, options = {}) {
    const {
      autoUpload = false,
      cloudConfig = null,
      maxBackups = 10,
      name = 'default'
    } = options;

    // 停止已存在的同名任务
    if (this.tasks.has(name)) {
      this.stopScheduledBackup(name);
    }

    const executeBackup = async () => {
      try {
        console.log(`开始执行定时备份任务: ${name}`);
        
        // 创建本地备份
        const backupResult = await this.backupManager.createBackup('scheduled');
        console.log(`本地备份创建成功: ${backupResult.filename}`);

        // 自动上传到云端
        if (autoUpload && cloudConfig) {
          try {
            const cloudManager = new CloudBackupManager(cloudConfig);
            await cloudManager.uploadBackup(backupResult.path, backupResult.filename);
            console.log(`备份已上传到云端: ${backupResult.filename}`);
          } catch (cloudError) {
            console.error('上传到云端失败:', cloudError);
          }
        }

        // 清理旧备份
        try {
          const cleanupResult = await this.backupManager.cleanupBackups(maxBackups);
          if (cleanupResult.deletedCount > 0) {
            console.log(`清理了 ${cleanupResult.deletedCount} 个旧备份`);
          }
        } catch (cleanupError) {
          console.error('清理备份失败:', cleanupError);
        }

        console.log(`定时备份任务完成: ${name}`);
      } catch (error) {
        console.error(`定时备份任务失败: ${name}`, error);
      }
      
      // 计算下次执行时间并重新设置定时器
      const nextTime = this.getNextExecutionTime(cronExpression);
      const delay = nextTime.getTime() - Date.now();
      const timerId = setTimeout(executeBackup, delay);
      this.timers.set(name, timerId);
      
      console.log(`下次备份时间: ${nextTime.toLocaleString()}`);
    };

    // 立即执行第一次备份
    executeBackup();
    
    this.tasks.set(name, {
      cronExpression,
      options,
      running: true
    });
    
    console.log(`定时备份任务已启动: ${name}, 表达式: ${cronExpression}`);
    
    return {
      success: true,
      taskName: name,
      cronExpression: cronExpression
    };
  }

  // 停止定时备份任务
  stopScheduledBackup(name) {
    const task = this.tasks.get(name);
    const timerId = this.timers.get(name);
    
    if (timerId) {
      clearTimeout(timerId);
      this.timers.delete(name);
    }
    
    if (task) {
      task.running = false;
      this.tasks.delete(name);
      console.log(`定时备份任务已停止: ${name}`);
      return { success: true, taskName: name };
    }
    
    return { success: false, message: '任务不存在' };
  }

  // 获取所有活动任务
  getActiveTasks() {
    const tasks = [];
    for (const [name, task] of this.tasks) {
      tasks.push({
        name: name,
        running: task.running || false,
        cronExpression: task.cronExpression
      });
    }
    return tasks;
  }

  // 停止所有任务
  stopAllTasks() {
    for (const [name, timerId] of this.timers) {
      clearTimeout(timerId);
    }
    this.timers.clear();
    this.tasks.clear();
    console.log('所有定时备份任务已停止');
    return { success: true };
  }

  // 验证 cron 表达式（简化版本）
  validateCronExpression(expression) {
    try {
      this.parseSimpleCron(expression);
      return true;
    } catch {
      return false;
    }
  }

  // 获取预设的 cron 表达式
  getPresetExpressions() {
    return {
      hourly: '0 * * * *',           // 每小时
      daily: '0 2 * * *',            // 每天凌晨2点
      weekly: '0 3 * * 0',           // 每周日凌晨3点
      monthly: '0 4 1 * *',          // 每月1号凌晨4点
      'every_6h': '0 */6 * * *',     // 每6小时
      'every_12h': '0 */12 * * *',   // 每12小时
      'workdays': '0 2 * * 1-5',     // 工作日凌晨2点
      'weekends': '0 3 * * 6,0'      // 周末凌晨3点
    };
  }
}

// 全局调度器实例
const scheduler = new BackupScheduler();

export default scheduler;
